//
//  WAIdentityAuthController.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/16.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "WAIdentityAuthController.h"
#import <QiniuSDK.h>

typedef NS_ENUM(NSInteger, WAAuthTextTFType) {
    WAAuthTextTF_ID,
    WAAuthTextTF_NickName,
    WAAuthTextTF_Sex,
    WAAuthTextTF_IDCard,
    WAAuthTextTF_Name,
    WAAuthTextTF_BankName,
    WAAuthTextTF_CardNum
};

@interface WAIdentityAuthController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;

//各种输入框

@property (weak, nonatomic) IBOutlet UITextField *idTF;
@property (weak, nonatomic) IBOutlet UITextField *nickNameTF;
@property (weak, nonatomic) IBOutlet UITextField *IDCardTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTF;
@property (weak, nonatomic) IBOutlet UITextField *backCardNumTF;


@property (strong, nonatomic) UIImage *selectedImage;
@end

@implementation WAIdentityAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.idTF.tag = WAAuthTextTF_ID;
    self.idTF.userInteractionEnabled = NO;
    self.nickNameTF.tag = WAAuthTextTF_NickName;
    self.IDCardTF.tag = WAAuthTextTF_IDCard;
    self.nameTF.tag = WAAuthTextTF_Name;
    self.bankNameTF.tag = WAAuthTextTF_BankName;
    self.backCardNumTF.tag = WAAuthTextTF_CardNum;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self updateViews];
    
    
    self.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageAction)];
    [self.headImageView addGestureRecognizer:tap];
}

- (void)updateViews{
    WNUserInfo *info = self.loginManager.userInfo;
    self.idTF.text =[@(info.userid) stringValue];
    self.nickNameTF.text = info.nickname;
    self.IDCardTF.text = info.cardid;
    self.nameTF.text = info.name;
    self.bankNameTF.text = info.bankname;
    self.backCardNumTF.text = info.cardnum;
    
    
    if ([info.headimage hasPrefix:@"http"]) {
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:info.headimage] placeholderImage:[UIImage imageNamed:@"head_default_photo"]];
    }else if (info.headimage.length > 0) {
        self.headImageView.image = [UIImage stringToImage:info.headimage];
    }else{
        self.headImageView.image = [UIImage imageNamed:@"head_default_photo"];
    }
    
    if (info.name.length > 0) {
        self.nameTF.userInteractionEnabled = NO;
    }else{
        self.nameTF.userInteractionEnabled = YES;
    }
    
    if (info.name.length > 0) {
        self.backCardNumTF.userInteractionEnabled = NO;
    }else{
        self.backCardNumTF.userInteractionEnabled = YES;
    }
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self returnWithTF:textField];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 0) {
        return YES;
    }else{
        if (textField.text.length > 18 && ![string isEqualToString:@""]) {
            return NO;
        }
        return YES;
    }
}

- (void)returnWithTF:(UITextField *)textField{
    switch (textField.tag) {
        case WAAuthTextTF_ID:
            {
                NSLog(@"--ID:%@",textField.text);
            }
            break;
        case WAAuthTextTF_NickName:
            {
                NSLog(@"--NickName:%@",textField.text);
            }
            break;
        case WAAuthTextTF_Sex:
            {
                NSLog(@"--Sex:%@",textField.text);
            }
            break;
        case WAAuthTextTF_IDCard:
            {
                NSLog(@"--Wechat:%@",textField.text);
            }
            break;
        case WAAuthTextTF_Name:
            {
                NSLog(@"--Name:%@",textField.text);
            }
            break;
        case WAAuthTextTF_BankName:
            {
                NSLog(@"--BankName:%@",textField.text);
            }
            break;
        case WAAuthTextTF_CardNum:
            {
                NSLog(@"--CardNum:%@",textField.text);
            }
            break;
        default:
            break;
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyBoardframe = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat spaceH = 40;
        // 强迫症，不能忍警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    UITextField *tf = [self.view.window performSelector:@selector(firstResponder)];
#pragma clang diagnostic pop
    CGRect rect1 = [self.view  convertRect:tf.frame fromView:tf.superview];
    CGFloat margin = keyBoardframe.size.height + spaceH - (WNScreenHeight - CGRectGetMaxY(rect1));
    if (margin <= 0) {
        return;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformMakeTranslation(0, - margin);
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformIdentity;
    }];
}
- (IBAction)commitAction:(id)sender {
    if (self.selectedImage) {
        [self updateUserInfoImage];
    }else{
        [self updateUserInfoWithImageUrl:nil];
    }
}

- (void)tapImageAction{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.scaleAspectFillCrop = YES;
    @weakify(self)
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        UIImage *image = photos.firstObject;
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            self.selectedImage = image;
            self.headImageView.image = image;
        });
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)updateUserInfoImage{
    [WNTool showLoadingMessage:@"正在提交..."];
    NSString *imageName = [NSString stringWithFormat:@"%@-%@",self.userID_String,[NSDate getNowTimeTimestamp]];
    [WAQiniuMananger uploadImage:self.selectedImage key:imageName progressHandler:^(NSString *key, float percent) {
        NSLog(@"--percent-%.1f",percent);
    } complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if ([key hasPrefix:@"http"]) {
            [self updateUserInfoWithImageUrl:key];
        }else{
            [WNTool show:key];
        }
    }];
    
}

- (void)updateUserInfoWithImageUrl:(NSString *)imageUrl{
        WNUserInfo *info = [WNUserInfo new];
        info.name = self.nameTF.text;
        info.bankname = self.bankNameTF.text;
        info.nickname = self.nickNameTF.text;
        info.cardid = self.IDCardTF.text;
        info.cardnum = self.backCardNumTF.text;
        info.userid = self.loginManager.userInfo.userid;
        if ([imageUrl hasPrefix:@"http"]) {
            info.headimage = imageUrl;
        }
    
        [WNBusinessRequest updateUserInfoWithModel:info Succ:^(id  _Nonnull responseObject) {
            [self.loginManager updateUserHeadImageAndUserInfo:nil];
            [WNTool show:@"提交成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self backAction:nil];
            });
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            NSLog(@"");
            [WNTool show:mes];
        }];
}


@end
